import 'dart:convert';

import 'package:base_flutter/base_flutter.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/message/message_config.dart';
import 'package:ls_work/net/api/http_api.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/viewmodel/service_execute/service_execute_base_view_model.dart';

import '../../net/response/service_execute/service_execute_list_data.dart';
import '../../util/speak_text_service.dart';

class ServiceExecuteListViewModel
    extends ServiceExecuteBaseViewModel<ServiceExecuteListData> {
  final String? elderCode;
  final String? status;
  final String? customerElderId;

  bool canBatch = false;

  void batchClick(ServiceExecuteListData item){
    if(item.resultMode!=0){
      return;
    }
    if(selectItems.contains(item)){
      selectItems.remove(item);
    }else{
      selectItems.add(item);
      SpeakTextService.speak(item.expenseItem??"");
    }
    notifyListeners();
  }

  void allClick(bool chooseAll){
    selectItems.clear();
    if(chooseAll){
      for(var item in listItems){
        if(item.resultMode==0){
          selectItems.add(item);
        }
      }
    }
    notifyListeners();
  }


  bool hasAllChoosed(){
    var list =  listItems.where((element) => element.resultMode==0);
    return selectItems.length == list.length;
  }

  var selectItems =  <ServiceExecuteListData>[];

  ServiceExecuteListViewModel(BuildContext context,
      {this.elderCode, this.status, this.customerElderId,this.canBatch = false})
      : super(context);

  var planFinishDate = DateTime.now().toDateStr([yyyy, '-', mm, '-', dd]);

  @override
  Future<List<ServiceExecuteListData>> requestListData() async {
    var result = await PostRequest.oldServicePlanList(
        elderCode, customerElderId, planFinishDate, status,page: page,rows: pageLength);
    if ("0" == result['code']) {
      var list = ((result['data']['rows'] as List?)??[])
          .map((e) => ServiceExecuteListData.fromJson(e))
          .toList();
      list.sort((o1,o2){
        return (o1.planStartTime??"").compareTo(o2.planStartTime??"");
      });

      // list.sort((o1,o2){
      //   return (o1.planTimeFlag??0).compareTo(o2.planTimeFlag??0);
      // });
      return list;
    } else {
      throw result['msg'].toString();
    }
  }

  @override
  int get pageLength => 100;


  @override
  void onCreated() {
    super.onCreated();
    requestRefresh();
  }

  @override
  void onRefresh() {
    super.onRefresh();
    requestRefresh();
  }

  @override
  Future<void> requestRefresh({bool showAni = true}) {
    sendMessage(SendMessageEvent(MessageConfig.REFRESH_PLAN_STATISTICS));
    return super.requestRefresh(showAni: showAni);
  }

  @override
  void receiveMessage(SendMessageEvent event) {
    super.receiveMessage(event);
    if(event.msgCode==MessageConfig.ENABLE_BATCH){
      canBatch = event.obj;
      notifyListeners();
    }
  }

  bool get showBatchBtn => selectItems.isNotEmpty&&canBatch;

  Future<void> batchSubmit() async {
    List tempList = [];
    for (var item in selectItems) {
      Map<String, dynamic> map = {};
      map["id"] = item.id;
      map["executeStatus"] = 0;
      map["finishTime"] =
          DateTime.now().toDateStr([yyyy,'-',mm,'-',dd,' ',HH,':',nn,':',ss]);
      map["remark"] = item.remark;
      if (item.bizParams.length > 0) {
        var temp = [];
        for (var i = 0; i < item.bizParams.length; i++) {
          temp.add({
            'value': "",
            'rangeTo': item.bizParams[i].rangeTo ?? "",
            'rangeFrom': item.bizParams[i].rangeFrom ?? "",
            'subItem': item.bizParams[i].subItem,
          });
        }
        map['result'] = jsonEncode(temp);
      }
      tempList.add(map);
    }
    showLoadingDialog(msg: '提交中...');
    try{
      var result = await HttpGo.instance.postData(HttpApi.executeServicePlanRecordBatch,data:{"jsonStr":jsonEncode(tempList)},options:
      PostRequest.urlencodedHeader);
      hideDialog();
      if("0"==result['code'].toString()){
        requestRefresh();
      }else{
        showToast(result['msg'].toString());
      }
    }catch(e){
      showToast(NetErrorUtils.getNetError(e));
      hideDialog();
    }
  }

  void sendToFamily(){
    showLoadingDialog(msg: "发送中...");
    Future.delayed(Duration(milliseconds: 1200),(){
      showToast("发送成功");
      hideDialog();
    });
  }
}
